package com.myhome.money.base.test;

import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;

/**
 * @author 蒋时华
 * 权限计算帮助类
 */
public class PermissionSumUtil {

    public static void main(String[] args) {
        List<Integer> integers = Arrays.asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
        String s = PermissionSumUtil.sumPermission(integers);
        System.out.println(s);
        System.out.println(PermissionSumUtil.testPermission(s, 1));
        System.out.println(PermissionSumUtil.testPermission(s, 19));
    }

    /**
     * 利用BigInteger对权限进行2的权的和计算
     *
     * @param permission int型权限编码数组
     * @return 2的权的和
     */
    public static String sumPermission(List<Integer> permission) {
        BigInteger num = new BigInteger("0");
        for (int i = 0; i < permission.size(); i++) {
            num = num.setBit(permission.get(i));
        }
        return num.toString();
    }

    /**
     * 利用BigInteger对权限进行2的权的和计算
     *
     * @param permission String型权限编码数组
     * @return 2的权的和
     */
    public static String sumPermission(String[] permission) {
        BigInteger num = new BigInteger("0");
        for (int i = 0; i < permission.length; i++) {
            num = num.setBit(Integer.parseInt(permission[i]));
        }
        return num.toString();
    }

    /**
     * 测试是否具有指定编码的权限
     *
     * @param sum
     * @param targetPermission
     * @return
     */
    public static boolean testPermission(BigInteger sum, int targetPermission) {
        return sum.testBit(targetPermission);
    }

    /**
     * 测试是否具有指定编码的权限
     *
     * @param sum
     * @param targetPermission
     * @return
     */
    public static boolean testPermission(String sum, int targetPermission) {
        if (StringUtils.isEmpty(sum)) {
            return false;
        }
        return testPermission(new BigInteger(sum), targetPermission);
    }

    /**
     * 测试是否具有指定编码的权限
     *
     * @param sum
     * @param targetPermission
     * @return
     */
    public static boolean testPermission(String sum, String targetPermission) {
        if (StringUtils.isEmpty(sum)) {
            return false;
        }
        return testPermission(new BigInteger(sum), targetPermission);
    }

    /**
     * 测试是否具有指定编码的权限
     *
     * @param sum
     * @param targetPermission
     * @return
     */
    public static boolean testPermission(BigInteger sum, String targetPermission) {
        return testPermission(sum, Integer.parseInt(targetPermission));
    }
}
